
<template>
  <div style="margin-bottom: 10px">
    <t-button variant="text" theme="primary"  @click="isDialogDevice = true">
      <span style="color: #fff">当前套餐音频模板数：{{memberInfo.voices}}/{{memberInfo.js_voices+memberInfo.jl_voices}}</span>
      &nbsp; &nbsp;&nbsp;&nbsp;立即升级
    </t-button>
  </div>
    <t-tabs v-model="value" @change="handlerChange" style="height: 100%">
      <t-tab-panel :value="item.value" :label="item.label" :destroy-on-hide="false" v-for="(item,key) in tabList" :key="key">
      <div style="padding: 20px;">
        <div style="margin-bottom: 20px; display: flex;justify-content: space-between;align-items: center">


          <t-button theme="primary" @click="openAdd">
            新增音频
          </t-button>
        </div>

        <t-table
            row-key="index"
            :data="data"
            :columns="columns"
            table-layout="auto"
            max-height="600px"
            cell-empty-content="-"
            lazy-load
        >
          <template #status="{ row }">
            <span v-if="row.status === 1" style="color: #4ade80">正常</span>
            <span v-else-if="row.status === 2" >生成中</span>
            <span style="color: red" v-else>生成失败:{{row.error_msg}}</span>
          </template>
          <template #model_type="{ row }">
            <span v-if="row.model_type === 'cicada1.0'" >Tacotron1</span>
            <span v-else-if="row.model_type === 'cicada3.0'" >Tacotron2</span>
            <span  v-else>-</span>
          </template>
          <template #audio_path="{ row }">
            <template v-if="row.audio_path">
              <audio :src="row.audio_path" controls style="height: 30px;width: 210px" ></audio>
            </template>
            <template v-else>
              <span>暂无预览文件</span>
            </template>
          </template>
          <template #operation="{ row }">
              <t-button theme="primary" variant="text" @click="openEdit(row)">重新生成</t-button>
              <t-button theme="danger" variant="text" @click="openDelete(row)" >删除</t-button>

          </template>
        </t-table>

      </div>


      </t-tab-panel>




    </t-tabs>


      <t-dialog
          v-model:visible="isDialogEdit"
          :header="DialogEditHeader"
          width="50%"
          confirmBtn="保存"
          @confirm="save"
      >
        <t-form label-align="left">
          <t-card bordered>
            <t-form-item label="音频名称"  >
              <t-input  v-model="formData.name"  placeholder="请输入内容" />
            </t-form-item>
            <t-form-item label="上传MP3文件" help="Tips：录制环境要安静，无背景杂音，正常语速，嚼字清晰，连续讲话不低于8秒，最好带有情感讲话 时长30秒-5分钟，文件大小不超过 100 M" >
              <t-upload
                  v-model="files"
                  accept=".mp3"
                  action="http://dev.blueant.pro/base/api.upload/file"
                  :abridge-name="[8, 6]"
                  theme="file-input"
                  placeholder="请选择需要上传的MP3文件"
                  @fail="handleFail"
              ></t-upload>
            </t-form-item>
            <t-form-item label="模型类型" help="Tips：cicada1.0 更贴近原始音色,cicada3.0 更贴近文案情感的朗读韵律" >
              <t-radio-group v-model="formData.model_type">
                <t-radio-button :value="model_type.value" v-for="(model_type, index) in model_types" :key="index" >{{model_type.label}}</t-radio-button>

              </t-radio-group>
            </t-form-item>
            <t-form-item label="音频情绪"  >
              <t-radio-group v-model="formData.emotion">
                <t-radio-button :value="emotion" v-for="(emotion, index) in emotions" :key="index" >{{emotion}}</t-radio-button>

              </t-radio-group>
            </t-form-item>

          </t-card>
          <p style="color: red;margin-top: 10px;">Tips：音频模板提交即产生费用，所以无法修改，请谨慎选择后再提交</p>
        </t-form>

  </t-dialog>


  <t-dialog
      v-model:visible="visible3"
      theme="warning"
      header="操作确认"
      body="确然要删除该条数据吗?"
      :cancel-btn="null"
      @confirm="onClickConfirm"
  />


  <t-dialog
      v-model:visible="isDialogDevice"
      header="音频模板加量包"
      width="50%"
      :footer="false"
  >
    <!-- 通过 props 传递参数 -->
    <DeviceView v-if="isDialogDevice" :item="deviceInfo"  />
  </t-dialog>
  <t-loading :loading="loading" text="加载中..." fullscreen />
</template>


<script setup >
import { ref } from 'vue';
import {get,post} from "@/utils/api";
import config from "@/config";
import {DialogPlugin, MessagePlugin} from 'tdesign-vue-next';
import DeviceView from "@/views/member/DeviceView.vue";
import {UserVipIcon} from "tdesign-icons-vue-next";
const value = ref("蝉镜");
const isDialogDevice = ref(false)
const tabList = ref([
  { label: '标准', value: '蝉镜' },
   //{ label: 'MINIMAX', value: 'MINIMAX' },

]);
const deviceInfo = ref({
  type:2,
  orderType:4
})
const visible3 = ref(false);
const isDialogEdit = ref(false);
const DialogEditHeader = ref("编辑音频");
const delId = ref(0);
const model_types = ref([
    {
      value: "cicada1.0",
      label: "Tacotron1"
    },
    {
      value: "cicada3.0",
      label: "Tacotron2"
    }
]);
const emotions = ref(["高兴", "悲伤", "愤怒", "恐惧", "厌恶", "惊讶", "中性"]);

const getVideoList = async () => {
  console.log("getConfigList");
  try {
    const response = await get(config.getVideoList,{
      platform_name:value.value,
      type:1
    }); // Adjust API endpoint as needed
    if (response.status === 200) {
      data.value  = response.data.data;
      console.log("getVideoList",data)
     // data.value = data;
    } else {
      console.error('Failed to fetch feedback data');
    }
  } catch (error) {
    console.error('Error fetching feedback data:', error);
  }


};
getVideoList()


const columns = ref([
  { colKey: 'name', title: '音频名称' },
  { colKey: 'code', title: '音频ID' },
  { colKey: 'status', title: '音频状态'},
  { colKey: 'emotion', title: '音频情绪' },
  { colKey: 'model_type', title: '训练模型' },
  { colKey: 'audio_path', title: '音频预览' },
  { colKey: 'operation', title: '操作' },
]);

const data = ref([]);

// 打开弹窗并传递参数(扣费逻辑部分)
const openEditCf = (row) => {
  get(config.getPriceRule,{
    stage_tag:"voiceTemplate",
    platform:"蝉镜"
  }).then(res => {
    if(res.data.code===1){
      let price = res.data.data.price_per_unit;
      const confirmDia = DialogPlugin({
        header: '操作确认',
        body: '确认要重新生成吗?重新生成将扣除'+price+'蓝豆!',
        confirmBtn: '确认',
        cancelBtn: '取消',
        onConfirm: ({ e }) => {
          console.log('e: ', e);
          get(config.getBeanBalance,{}).then(res => {
            if(res.data.code===1){
              if(res.data.data.bean_balance>=price){
                confirmDia.hide();

                console.log(row);
                formData.value = row;
                isDialogEdit.value = true;
                DialogEditHeader.value = "编辑音频";
              }else{
                MessagePlugin.error('蓝豆余额不足')
              }
            }else{
              MessagePlugin.error(res.data.msg)
            }
          })




        },
        onClose: ({ e, trigger }) => {
          console.log('e: ', e);
          console.log('trigger: ', trigger);
          confirmDia.hide();
        },
      });
    }else{
      MessagePlugin.error(res.data.msg)
    }
  })

};

const openEdit = (row) => {
  const confirmDia = DialogPlugin({
    header: '操作确认',
    body: '确认要重新生成吗?重新生成将覆盖原音频模板!',
    confirmBtn: '确认',
    cancelBtn: '取消',
    onConfirm: ({ e }) => {
      console.log('e: ', e);
      confirmDia.hide();

      console.log(row);
      formData.value = row;
      isDialogEdit.value = true;
      DialogEditHeader.value = "重新生成";


    },
    onClose: ({ e, trigger }) => {
      console.log('e: ', e);
      console.log('trigger: ', trigger);
      confirmDia.hide();
    },
  });

};

const openAdd = () => {
  if(memberInfo.value.voices>=memberInfo.value.js_voices+memberInfo.value.jl_voices){
    MessagePlugin.error('当前音频模板已满')
  }else{
    isDialogEdit.value = true;
    DialogEditHeader.value = "新增音频";
  }

};


// 删除弹窗部分
const openDelete = (row) => {
  visible3.value = true;
  delId.value = row.id;
  console.log('删除的数据',row)
};
const onClickConfirm = async () => {
  try {
    const response = await get(config.delVideo,{id:delId.value}); // Adjust API endpoint as needed
    if (response.status === 200) {
      const data = response.data;
      if(data.code===1){
        MessagePlugin.success('删除成功')
      }else{
        MessagePlugin.error(data.info)
      }
      console.log(data)
     // MessagePlugin.success('删除成功')
      visible3.value = false;
      getVideoList()
    } else {
      console.error('Failed to fetch feedback data');
      MessagePlugin.error('删除失败')
    }
  } catch(error) {
    MessagePlugin.error('删除失败')
  }
  visible3.value = false;
 // getTableData();

  console.log('删除成功');
};


const handlerChange = (newValue) => {
  value.value = newValue;
  formData.value.platform_name = newValue;
  getVideoList()

 // getConfig()
};
const formData = ref({
  type:1,
  name:"",
  id:0,
  platform_name:value.value,
  code:"",
  file_url:"",
  model_type:"cicada1.0"
});
const loading = ref(false);
const save = async () => {

  console.log("files",files.value)
  if(files.value.length===0){
    MessagePlugin.error('请上传音频文件')
    return
  }
  if(files.value[0].percent<100){
    MessagePlugin.error('请等待音频文件上传完成')
    return
  }
  formData.value.file_url = files.value[0].response.data.url;
  console.log("formData",formData.value);
  loading.value = true;
  try {
    const response = await post(config.saveVideo,formData.value); // Adjust API endpoint as needed
    if (response.status === 200) {
      const data = response.data;
      loading.value = false;
      if(data.code===0){
        MessagePlugin.error(data.info)
        return;
      }else {
        console.log(data)
        MessagePlugin.success('保存成功')
        isDialogEdit.value = false;
        getVideoList()
      }

    } else {
      loading.value = false;
      console.error('Failed to fetch feedback data');
      MessagePlugin.error('保存失败')
    }
  } catch(error) {
    loading.value = false;
    MessagePlugin.error('保存失败')
  }
};

const files = ref([]);

const handleFail = ({ file }) => {
  MessagePlugin.error(`文件 ${file.name} 上传失败`);
};

const memberInfo = ref({})
const getMemberInfo = () => {
  get(config.getMemberInfo).then(res => {
    memberInfo.value = res.data.data
    console.log("getMemberInfo", res.data.data)
  })
}
getMemberInfo()

</script>
<style scoped>

</style>
